package app

import (
	"APT/internal/dao"
	"APT/internal/model/entity"
	"context"
	"database/sql"
	"errors"
	"github.com/gogf/gf/v2/frame/g"

	"github.com/gogf/gf/v2/errors/gerror"

	"APT/api/app/basics"
)

func (c *ControllerBasics) StaffFxCenter(ctx context.Context, req *basics.StaffFxCenterReq) (res *basics.StaffFxCenterRes, err error) {
	var (
		PmsAppStay []*entity.PmsAppStay
		MemberInfo *entity.PmsMember
		Staff      *entity.PmsStaff
	)
	res = new(basics.StaffFxCenterRes)
	if err = dao.PmsMember.Ctx(ctx).Where(g.MapStrAny{
		dao.PmsMember.Columns().StaffId:    req.StaffId,
		dao.PmsMember.Columns().RebateMode: "STAFF",
	}).Scan(&MemberInfo); err != nil && !errors.Is(err, sql.ErrNoRows) {
		return
	}
	if g.IsEmpty(MemberInfo) {
		err = gerror.New("员工信息不存在")
		return
	}
	if err = dao.PmsStaff.Ctx(ctx).Where(dao.PmsStaff.Columns().Id, req.StaffId).Scan(&Staff); err != nil && !errors.Is(err, sql.ErrNoRows) {
		return
	}
	if g.IsEmpty(Staff) {
		err = gerror.New("员工信息不存在")
		return
	}
	res.AllBrokerage = Staff.AllBalance
	res.Brokerage = Staff.Balance
	if err = dao.PmsAppStay.Ctx(ctx).Where(dao.PmsAppStay.Columns().Referrer, MemberInfo.Id).Page(1, 4).Scan(&res.BrokerageList); err != nil && !errors.Is(err, sql.ErrNoRows) {
		err = gerror.New("计算单数据异常")
		return
	}
	for k, v := range res.BrokerageList {
		if v.RebateStatus == "WAIT" {
			res.BrokerageList[k].RebateAmount += v.OrderAmount * (v.RebateRate / 100)
		}
	}
	// 结算中
	if err = dao.PmsAppStay.Ctx(ctx).Where(g.MapStrAny{
		dao.PmsAppStay.Columns().Referrer:     MemberInfo.Id,
		dao.PmsAppStay.Columns().RebateStatus: "WAIT",
	}).Scan(&PmsAppStay); err != nil && !errors.Is(err, sql.ErrNoRows) {
		err = gerror.New("计算单数据异常")
		return
	}
	for _, v := range PmsAppStay {
		if v.RebateStatus == "WAIT" {
			res.SettlingBrokerage += v.OrderAmount * (v.RebateRate / 100)
		} else if v.RebateStatus == "SUCCESS" {
			//res.SettlingWithdraw += v.RebateAmount
		}
	}

	// 提现中金额
	res.SettlingWithdraw = Staff.ApplyWithdrawBalance
	// 已提现金额
	res.Withdraw = Staff.WithdrawBalance

	/*if res.SettlingWithdraw, err = dao.PmsWithdraw.Ctx(ctx).Where(g.MapStrAny{
		dao.PmsWithdraw.Columns().StaffId:        req.StaffId,
		dao.PmsWithdraw.Columns().WithdrawStatus: "WAIT",
	}).Sum(dao.PmsWithdraw.Columns().WithdrawAmount); err != nil {
		err = gerror.New("计算单数据异常")
		return
	}*/

	return
}
